/**
 * 导出的一个保存商品的方法
 * 这个我们的约定，约成成对象，好操作一些
 * goods ==> {goods_id:129,goods_number:1}
 */
const KEY = "GOODS"
export const getLocalGoods = () => {
    return wx.getStorageSync(KEY) || {}
}

export const addGoods = ({goods_id,goods_number})=>{
    //1.取出本地存储的商品对象{goods_id,goods_number},假设本地{38:1,129:1}
    const localGoods = wx.getStorageSync(KEY) || {}
    // console.log(localGoods);
    
    //2. 根据传递过来的id,去取出来的本地的商品对象,看传递过来的id是否在本地存在
    // 判断，如果存在就累加，不存在就新增一个
    if(localGoods[goods_id]){
        localGoods[goods_id] += goods_number
    }else {
        localGoods[goods_id] = goods_number
    }   

    //3. 保存回去
    wx.setStorageSync(KEY, localGoods)
}

export const deleteGoods = goods_id => {
    // 1、取出本地存储的商品对象 {goods_id:goods_number}，假设本地{38:1,129:1}
    const localGoods = wx.getStorageSync(KEY) || {}
    // 2、删除id对应的商品数据
    delete localGoods[goods_id]

    // 3、保存回去
    wx.setStorageSync(KEY, localGoods)
}

export const updateGoods = ({ goods_id, goods_number }) => {
    // 1、取出本地存储的商品对象 {goods_id:goods_number}，假设本地{38:1,129:1}
    const localGoods = wx.getStorageSync(KEY) || {}
  
    // 2、更改商品数量
    localGoods[goods_id] = goods_number
  
    // 3、保存回去
    wx.setStorageSync(KEY, localGoods)
  }